package com.yjt.fresh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.adpater.adpsection.AdpRvAtyBalance;
import com.yjt.fresh.adpater.adpsection.OnSectionItemClickListener;
import com.yjt.fresh.adpater.adpsection.SectionedSpanSizeLookup;
import com.yjt.fresh.api.ApiGetCouponsForPay;
import com.yjt.fresh.api.ApiGetDefaultAddress;
import com.yjt.fresh.api.ApiOrder;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanAddress;
import com.yjt.fresh.bean.BeanCart;
import com.yjt.fresh.bean.BeanCartChange;
import com.yjt.fresh.bean.BeanCouponForPay;
import com.yjt.fresh.bean.BeanGetProductAddress;
import com.yjt.fresh.bean.BeanOrderResult;
import com.yjt.fresh.bean.BeanStoreCoupon;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.ScrollGridLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 结算页面
 * Created by mcc on 2018/7/31.
 */

public class AtyBalance extends BaseSimpleActivity {
    private static final int REQUEST_CODE = 1006;
    private static final int INVOICE_REQUEST_CODE = 1007;
    private static final int COUPON_REQUEST_CODE = 1008;
    @BindView(R.id.back)
    RelativeLayout mBack;
    @BindView(R.id.rvAppAtyBalance)
    RecyclerView mRv;
    @BindView(R.id.tvAppAtyBalancePrice)
    TextView mTvPrice;
    @BindView(R.id.tvAppAtyBalancePay)
    TextView mTvPay;
    @BindView(R.id.tvAppAtyBalanceAddAddress)
    TextView mTvAddAddress;
    @BindView(R.id.rlAppAtyBalanceAddAddress)
    RelativeLayout mRlAddAddress;
    @BindView(R.id.tvAppAtyBalanceReceiveName)
    TextView mTvReceiveName;
    @BindView(R.id.tvAppAtyBalanceReceivePhone)
    TextView mTvReceivePhone;
    @BindView(R.id.tvAppAtyBalanceAddress)
    TextView mTvAddress;
    @BindView(R.id.llAppAtyBalanceAddress)
    LinearLayout mLlAddress;
    private List<BeanCartChange> mBeanCartChanges = new ArrayList<>();
    private AdpRvAtyBalance mAdpRvAtyBalance;
    private TextView mTvFoot;
    private int mInvoicePosition;
    private int mCouponPosition;
    private BeanAddress mAddress;
    private double mNeedMoney;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_balance;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initEvent() {
        initRV();
        initClick();
        getData();
    }

    HttpOnNextListener<BeanGetProductAddress> mGetAddressListener = new HttpOnNextListener<BeanGetProductAddress>() {
        @Override
        public void onNext(BeanGetProductAddress beanAddress) {
            if (beanAddress != null) {
                mAddress = new BeanAddress();
                mAddress.setRECEIVER_NAME(beanAddress.getRECEIVER_NAME());
                mAddress.setRECEIVER_PHONE(beanAddress.getRECEIVER_PHONE());
                mAddress.setPROVINCE(beanAddress.getPROVINCE());
                mAddress.setCITY(beanAddress.getCITY());
                mAddress.setAREA(beanAddress.getAREA());
                mAddress.setRECEIVER_ADDRESS(beanAddress.getRECEIVER_ADDRESS());

                mRlAddAddress.setVisibility(View.GONE);
                mLlAddress.setVisibility(View.VISIBLE);
                mTvReceiveName.setText(beanAddress.getRECEIVER_NAME());
                mTvReceivePhone.setText(beanAddress.getRECEIVER_PHONE());
                mTvAddress.setText(beanAddress.getPROVINCE() + beanAddress.getCITY() + beanAddress.getAREA() + beanAddress.getRECEIVER_ADDRESS());

            } else {
                mRlAddAddress.setVisibility(View.VISIBLE);
                mLlAddress.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getData() {
        ApiGetDefaultAddress apiGetDefaultAddress = new ApiGetDefaultAddress(mGetAddressListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiGetDefaultAddress.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetDefaultAddress);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void eventBusReceive(List<BeanCartChange> list) {
        mNeedMoney = 0;
        mBeanCartChanges = list;
        for (int i = 0; i < mBeanCartChanges.size(); i++) {
            List<BeanCart> beanCarts = mBeanCartChanges.get(i).getBeanCarts();
            for (int j = 0; j < beanCarts.size(); j++) {
                mNeedMoney += beanCarts.get(j).getCOUNT() * beanCarts.get(j).getGOODINFO().getSINGLE_PRICE();
            }
        }
        mNeedMoney = CommonsToolsHelper.getTwoDecimal(mNeedMoney);
        mTvPrice.setText(mNeedMoney + "");
        for (int i = 0; i < list.size(); i++) {
            List<BeanCart> beanCarts = list.get(i).getBeanCarts();
            String storeId = beanCarts.get(0).getSTORE_ID();
            double orderMoney = 0;
            for (int j = 0; j < beanCarts.size(); j++) {
                orderMoney += beanCarts.get(j).getGOODINFO().getSINGLE_PRICE();
            }
            getCouponData(i, storeId, orderMoney);
        }
    }


    private void getCouponData(final int position, String storeId, double orderMoney) {
        ApiGetCouponsForPay apiGetCouponsForPay = new ApiGetCouponsForPay(new HttpOnNextListener<ArrayList<BeanStoreCoupon>>() {
            @Override
            public void onNext(ArrayList<BeanStoreCoupon> list) {
                mBeanCartChanges.get(position).setCouponForPays(list);
                mAdpRvAtyBalance.notifyDataSetChanged();
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("OWNER", storeId);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("ORDER_MONEY", orderMoney);
        apiGetCouponsForPay.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetCouponsForPay);
    }

    private void initClick() {
        mAdpRvAtyBalance.setOnSectionItemClickListener(new OnSectionItemClickListener() {
            @Override
            public void onSectionItemClick(int type, int section, int position, int viewID, TextView tv, TextView tvCouponMoney) {

                if (type == MyConstants.BALANCE_ITEM_FOOT) {
                    mTvFoot = tv;
                    if (viewID == R.id.rlAppRecycleItemAtyBalanceFootInvoice) {//开发票
                        mInvoicePosition = section;
                        Intent intent = new Intent(mContext, AtyInvoice.class);
                        double totalPrice = 0;
                        List<BeanCart> goodsList = mBeanCartChanges.get(section).getBeanCarts();
                        for (int i = 0; i < goodsList.size(); i++) {
                            totalPrice += goodsList.get(i).getGOODINFO().getSINGLE_PRICE() * goodsList.get(i).getCOUNT();
                        }
                        intent.putExtra(MyConstants.INVOICE_MONEY, totalPrice);
                        BeanCartChange beanCartChange = mBeanCartChanges.get(mInvoicePosition);
                        intent.putExtra(AtyInvoice.INVOICE_CONTENT, beanCartChange.getInvoiceContent() == null ? "" : beanCartChange.getInvoiceContent());
                        intent.putExtra(AtyInvoice.TAX_NUM,beanCartChange.getInvoiceTaxNum() == null ? "" : beanCartChange.getInvoiceTaxNum());
                        intent.putExtra(AtyInvoice.INVOICE_TITLE,beanCartChange.getInvoiceTitle() == null ? "" : beanCartChange.getInvoiceTitle());
                        intent.putExtra(AtyInvoice.INVOICE_TYPE,beanCartChange.getInvoiceType() == null ? "" : beanCartChange.getInvoiceType());
                        startActivityForResult(intent, INVOICE_REQUEST_CODE);
                    } else if (viewID == R.id.rlAppRecycleItemAtyBalanceFootCoupon) {
                        mCouponPosition = section;
                        if (mBeanCartChanges.get(section).getCouponForPays() != null && mBeanCartChanges.get(section).getCouponForPays().size() > 0) {
                            ArrayList<BeanStoreCoupon> beanStoreCouponList = mBeanCartChanges.get(section).getCouponForPays();
                            Intent intent = new Intent(mContext, AtyCouponForPay.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelableArrayList(MyConstants.COUPON_OBJ, beanStoreCouponList);
                            intent.putExtra(MyConstants.COUPON_OBJ, bundle);
                            startActivityForResult(intent, COUPON_REQUEST_CODE);
                        }
                    }
                }
            }
        });

        mTvPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAddress != null) {
                    pay();
                } else {
                    Toast.makeText(mContext, "请先选择收获地址", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mTvAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyAddresses.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        mLlAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyAddresses.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    HttpOnNextListener<BeanOrderResult> mOrderListener = new HttpOnNextListener<BeanOrderResult>() {
        @Override
        public void onNext(BeanOrderResult beanOrderResult) {
            Intent intent = new Intent(mContext, AtyPay.class);
            intent.putExtra(MyConstants.ORDER_INFO, beanOrderResult);
            intent.putExtra(MyConstants.FROM_WHERE, MyConstants.BALANCE);
            intent.putExtra(MyConstants.ORDER_MONEY, mNeedMoney);
            startActivity(intent);
            finish();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void pay() {
        String orderInfo = "";
        for (int i = 0; i < mBeanCartChanges.size(); i++) {
            orderInfo += mBeanCartChanges.get(i).getBeanCarts().get(0).getSTORE_ID();
            orderInfo += "LM" + mAddress.getRECEIVER_NAME();
            orderInfo += "LM" + mAddress.getRECEIVER_PHONE();
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getRemark()) ? "" : mBeanCartChanges.get(i).getRemark());
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getInvoiceTitle()) ? "" : mBeanCartChanges.get(i).getInvoiceTitle());
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getInvoiceTaxNum()) ? "" : mBeanCartChanges.get(i).getInvoiceTaxNum());
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getInvoiceContent()) ? "" : mBeanCartChanges.get(i).getInvoiceContent());
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getInvoiceType()) ? "" : mBeanCartChanges.get(i).getInvoiceType());
            orderInfo += "LM" + mAddress.getRECEIVER_ADDRESS();
            orderInfo += "LM" + mAddress.getPROVINCE();
            orderInfo += "LM" + mAddress.getCITY();
            orderInfo += "LM" + mAddress.getAREA();
            orderInfo += "LM" + (TextUtils.isEmpty(mBeanCartChanges.get(i).getCouponID()) ? "" : mBeanCartChanges.get(i).getCouponID()) + "LM";
            List<BeanCart> beanCarts = mBeanCartChanges.get(i).getBeanCarts();
            for (int j = 0; j < beanCarts.size(); j++) {
                if (j < 1) {
                    orderInfo += beanCarts.get(j).getCHILDGOODS_ID();
                } else {
                    orderInfo += "CC" + beanCarts.get(j).getCHILDGOODS_ID();
                }
                BeanCart.GOODINFOBean childGoodsInfo = beanCarts.get(j).getGOODINFO();
                if (childGoodsInfo.getGOODS_SPEC_TYPE() == 1) {
                    orderInfo += "ML" + "单品";
                } else if (childGoodsInfo.getGOODS_SPEC_TYPE() == 2) {
                    orderInfo += "ML" + childGoodsInfo.getONE_SPEC_TYPE() + ":" + childGoodsInfo.getONE_SPEC_CONTENT();
                } else if (childGoodsInfo.getGOODS_SPEC_TYPE() == 3) {
                    orderInfo += "ML" + childGoodsInfo.getONE_SPEC_TYPE() + ":" + childGoodsInfo.getONE_SPEC_CONTENT()
                            + ";" + childGoodsInfo.getTWO_SPEC_TYPE() + ":" + childGoodsInfo.getTWO_SPEC_CONTENT();
                }
                if (j == beanCarts.size() - 1) {
                    orderInfo += "ML" + beanCarts.get(j).getCOUNT() + "GX";
                } else {
                    orderInfo += "ML" + beanCarts.get(j).getCOUNT();
                }
            }
        }
        ApiOrder apiOrder = new ApiOrder(mOrderListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("ORDERSTRING", orderInfo);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiOrder.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiOrder);
    }

    private void initRV() {
        mAdpRvAtyBalance = new AdpRvAtyBalance(mContext, mBeanCartChanges);
        ScrollGridLayoutManager manager = new ScrollGridLayoutManager(mContext, 1);
        manager.setSpanSizeLookup(new SectionedSpanSizeLookup(mAdpRvAtyBalance, manager));
        mRv.setLayoutManager(manager);
        mRv.setAdapter(mAdpRvAtyBalance);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INVOICE_REQUEST_CODE && data != null) {//发票
            mBeanCartChanges.get(mInvoicePosition).setInvoiceContent(data.getStringExtra(AtyInvoice.INVOICE_CONTENT));
            mBeanCartChanges.get(mInvoicePosition).setInvoiceTaxNum(data.getStringExtra(AtyInvoice.TAX_NUM));
            mBeanCartChanges.get(mInvoicePosition).setInvoiceTitle(data.getStringExtra(AtyInvoice.INVOICE_TITLE));
            mBeanCartChanges.get(mInvoicePosition).setInvoiceType(data.getStringExtra(AtyInvoice.INVOICE_TYPE));
            mTvFoot.setText("已开具");
        }

        mNeedMoney = 0;
        for (int i = 0; i < mBeanCartChanges.size(); i++) {
            List<BeanCart> beanCarts = mBeanCartChanges.get(i).getBeanCarts();
            for (int j = 0; j < beanCarts.size(); j++) {
                mNeedMoney += beanCarts.get(j).getCOUNT() * beanCarts.get(j).getGOODINFO().getSINGLE_PRICE();
            }
        }
        mNeedMoney = CommonsToolsHelper.getTwoDecimal(mNeedMoney);
        if (requestCode == COUPON_REQUEST_CODE && data != null) {
            BeanStoreCoupon beanStoreCoupon = data.getParcelableExtra(MyConstants.COUPON_OBJ);
            BeanCartChange beanCartChange = mBeanCartChanges.get(mCouponPosition);
            beanCartChange.setCouponID(beanStoreCoupon.getCOUPON_ID());
            for (int i = 0; i < beanCartChange.getCouponForPays().size(); i++) {
                beanCartChange.getCouponForPays().get(i).setCheck(false);
            }
            beanCartChange.getCouponForPays().get(data.getIntExtra(MyConstants.COUPON_POSITION,0)).setCheck(true);
            if ("1".equals(beanStoreCoupon.getCOUPONTYPE())) {//满减
                beanCartChange.setCouponMoney(beanStoreCoupon.getCOUPON_REDUCE_MONEY());
                mNeedMoney = mNeedMoney - beanStoreCoupon.getCOUPON_REDUCE_MONEY();
                mTvPrice.setText("" + CommonsToolsHelper.getTwoDecimal(mNeedMoney));
            } else if ("2".equals(beanStoreCoupon.getCOUPONTYPE())) {//折扣
                double totalPrice = 0;
                List<BeanCart> goodsList = beanCartChange.getBeanCarts();
                for (int i = 0; i < goodsList.size(); i++) {
                    totalPrice += goodsList.get(i).getGOODINFO().getSINGLE_PRICE() * goodsList.get(i).getCOUNT();
                }
                beanCartChange.setCouponMoney(totalPrice * (1.0 - beanStoreCoupon.getDISCOUNT()));
                mNeedMoney = mNeedMoney - totalPrice * (1.0 - beanStoreCoupon.getDISCOUNT());
                mTvPrice.setText("" + CommonsToolsHelper.getTwoDecimal(mNeedMoney));
            }
            mAdpRvAtyBalance.notifyDataSetChanged();
        }else {
            BeanCartChange beanCartChange = mBeanCartChanges.get(mCouponPosition);
            ArrayList<BeanStoreCoupon> couponForPays = beanCartChange.getCouponForPays();
            for (int i = 0; i < couponForPays.size(); i++) {
                couponForPays.get(i).setCheck(false);
            }
            beanCartChange.setCouponID(null);
            beanCartChange.setCouponMoney(0);
            mTvPrice.setText("" + CommonsToolsHelper.getTwoDecimal(mNeedMoney));
            mAdpRvAtyBalance.notifyDataSetChanged();
        }

        if (resultCode == MyConstants.CHOOSE_ADDRESS){
            BeanAddress address = (BeanAddress) data.getSerializableExtra(MyConstants.ADDRESS_OBJ);
            mAddress = address;
            mRlAddAddress.setVisibility(View.GONE);
            mLlAddress.setVisibility(View.VISIBLE);
            mTvReceiveName.setText(address.getRECEIVER_NAME());
            mTvReceivePhone.setText(address.getRECEIVER_PHONE());
            mTvAddress.setText(address.getPROVINCE() + address.getCITY() + address.getAREA() + address.getRECEIVER_ADDRESS());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
